package com.mrx.xfriendship.controller;

import com.alibaba.fastjson2.JSONObject;
import com.mrx.commons.annotations.XLog;
import com.mrx.xfriendship.model.dto.*;
import com.mrx.xfriendship.model.vo.CommentVO;
import com.mrx.xfriendship.model.vo.ListPostPageVO;
import com.mrx.xfriendship.model.vo.PostVO;
import com.mrx.xfriendship.service.*;
import com.mrx.xfriendship.util.SecurityUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子相关 接口
 *
 * @author : 肖康宁
 * @since : 2023-01-13 14:54
 **/
@XLog
@Validated
@RestController
@RequestMapping("/post")
public class PostController {

    @DubboReference
    private IPostService postService;

    @DubboReference
    private ITagService tagService;

    @DubboReference
    private ICommentService commentService;

    private static final Logger logger = LoggerFactory.getLogger(PostController.class);

    @Resource
    private IMinioService minioService;

    @DubboReference
    private IUserService userService;

    @DubboReference
    private ISystemInfoService systemInfoService;

    /**
     * 获取 首页展示数据, 包含 tags, posts, onLineUserNumber
     *
     * @param pageVO 分页参数
     */
    @GetMapping("/index")
    public Result<IndexDTO> index(HttpServletRequest request, ListPostPageVO pageVO) {
        return Result.success(IndexDTO.of(
                        tagService.listTags(),
                        postService.listPosts(request.getRemoteAddr(), pageVO),
                        userService.onlineUserNumber(),
                        userService.maxOnlineUserNumber(),
                        systemInfoService.getSystemInfoByKey(ISystemInfoService.HEAD_PIC)
                )
        );
    }

    /**
     * 通过 tagId 查找 tag 信息
     *
     * @param id tag id
     */
    @GetMapping("/tagInfo")
    public Result<TagDTO> tagInfo(@RequestParam Integer id) {
        return Result.success(tagService.findTagById(id));
    }

    /**
     * 列出所有 帖子, 不推荐使用, list 和 tag 接口已经整合进了 index 接口
     *
     * @param pageVO 分页查询参数
     * @see #index(HttpServletRequest, ListPostPageVO)
     */
    @Deprecated
    @GetMapping("/list")
    public Result<PageDTO<PostDTO>> list(HttpServletRequest request, ListPostPageVO pageVO) {
        return Result.success(postService.listPosts(request.getRemoteAddr(), pageVO));
    }

    /**
     * 列出所有 tag, 不推荐使用, list 和 tag 接口已经整合进了 index 接口
     *
     * @see #index(HttpServletRequest, ListPostPageVO)
     */
    @Deprecated
    @GetMapping("/tags")
    public Result<List<TagDTO>> tags() {
        return Result.success(tagService.listTags());
    }

    /**
     * 获取 帖子详情
     *
     * @param id 帖子 id
     */
    @GetMapping("/detail")
    public Result<PostDTO> detail(@RequestParam Integer id) {
        return Result.success(postService.postDetail(id));
    }

    /**
     * 发表评论
     *
     * @param id      被评论的帖子 id
     * @param comment 评论内容
     */
    @PostMapping("/postComment")
    public Result<String> postComment(@RequestParam Integer id, @RequestBody CommentVO comment) {
        commentService.postComment(id, SecurityUtil.getCurrentUserId(), comment);
        return Result.success("回复成功");
    }

    /**
     * 发表帖子
     *
     * @param vo 帖子 内容
     */
    @PostMapping("/publishPost")
    public Result<String> publishPost(@RequestBody PostVO vo) {
        vo.setCreateUserId(SecurityUtil.getCurrentUserId());
        postService.publish(vo);
        return Result.success("发布成功");
    }

    /**
     * 上传图片
     *
     * @param file 图片文件
     */
    @PostMapping("/upload")
    public PostPicResult upload(MultipartFile file) {
        JSONObject json = JSONObject.of("errno", 0);
        try {
            String fileName = minioService.upload(file);
            String url = minioService.preview(fileName);
            JSONObject data = JSONObject.of(
                    "url", url,
                    "alt", file.getOriginalFilename(),
                    "href", url,
                    "fileName", fileName
            );
            json.put("data", data);
        } catch (Exception e) {
            logger.warn("图片上传失败", e);
            json.put("errno", 1);
            json.put("message", e.getLocalizedMessage());
        }
        return PostPicResult.newResult(json);
    }

}
